package com.example.common.util;

import com.example.common.api.IResultCode;
import com.example.common.api.ResultUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.io.IOException;

public class ResponseErrorUtil {

    public static Mono<Void> writeErrorMessage(ServerHttpResponse response, IResultCode resultCode) {
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        ObjectMapper mapper = new ObjectMapper();
        try{
            byte[] body = mapper.writeValueAsBytes(ResultUtil.failed(resultCode));
            DataBuffer dataBuffer = response.bufferFactory().wrap(body);
            return response.writeWith(Mono.just(dataBuffer));
        } catch (IOException e){
            e.printStackTrace();
        }

        return response.writeWith(Mono.empty());
    }
}
